package com.wxapi

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.ViewDataBinding
import com.jaeger.library.StatusBarUtil
import com.module.frame.base.BaseFrameViewModel
import com.module.frame.base.BaseVmVdbActivity
import com.module.frame.ext.observe
import com.module.frame.ext.postEvent
import com.module.third.R
import com.module.third.databinding.ThirdActivityWechatBinding
import com.module.third.ext.wxLoginSharedFlow
import com.module.third.wx.WxConfig
import com.module.third.wx.bean.WxToken
import com.module.third.wx.bean.WxUserInfo
import com.wxapi.model.WXEntryViewModel
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

open class MyWXEntryActivity<VM : WXEntryViewModel> : BaseVmVdbActivity<VM, ViewDataBinding>(),
    IWXAPIEventHandler {

    private val api: IWXAPI by lazy {
        WXAPIFactory.createWXAPI(this, WxConfig.WX_APP_ID, false)
    }
    private var resp: BaseResp? = null

    override fun bingViewModel() {
    }

    override fun getLayoutId(): Int {
        return R.layout.third_activity_wechat
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.window.decorView.setBackgroundColor(Color.TRANSPARENT)
    }

    protected fun setStatusBar() {
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null) //状态栏透明
        StatusBarUtil.setLightMode(this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        api.handleIntent(intent, this)
//        finish();
    }

    override fun initView() {
        super.initView()
        api.handleIntent(intent, this)
        setStatusBar()
        showLoading()
    }

    override fun initListener() {
        super.initListener()
        observe(mViewModel.failFlow) {
            geFail(it)
        }
        observe(mViewModel.tokenSucFlow) {
            getWxTokenSuc(it)
        }
        observe(mViewModel.infoSucFlow) {
            getWxInfoSuc(it)
        }
    }


    // 微信发送请求到第三方应用时，会回调到该方法
    override fun onReq(baseReq: BaseReq?) {
        finish()
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    override fun onResp(baseResp: BaseResp?) {
        var result = ""
        if (baseResp != null) {
            resp = baseResp
        }
        when (resp?.errCode) {
            BaseResp.ErrCode.ERR_OK -> if (!baseResp?.openId.isNullOrEmpty()) {
                finish()
                return
            } else {
                val code = (resp as SendAuth.Resp).code
                val state = (resp as SendAuth.Resp).state
                if (!code.isNullOrEmpty() && state == WxConfig.WX_LOGON_STATE) {
                    //获取token
                    mViewModel.getWxToken(
                        WxConfig.WX_APP_ID,
                        WxConfig.WX_SECRET,
                        code,
                        "authorization_code"
                    )
                    return
                }
                Toast.makeText(this, "貌似出了点差错，请稍后重试~", Toast.LENGTH_SHORT).show()
                finish()
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
                result = "取消"
                //                ToastUtils.showShort(R.string.login_failed);
                finish()
            }
            BaseResp.ErrCode.ERR_AUTH_DENIED -> //                result = "发送被拒绝";
//                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish()
            else -> //                result = "发送返回";
//                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish()
        }
    }

    open fun getWxTokenSuc(wxToken: WxToken) {
        mViewModel.getWxInfo(wxToken.accessToken, wxToken.openid)
    }

    open fun getWxInfoSuc(wxUserInfo: WxUserInfo?) {
        postEvent(wxLoginSharedFlow, wxUserInfo)
        finish()
    }

    open fun geFail(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
        finish()
    }

    override fun finish() {
        hideLoading()
        super.finish()
    }
}